/**
 * Created by chenxq on 2017/12/29.
 */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Tabs,DatePicker,Progress ,Modal,Table,message} from 'antd';
import {
  ChartCard,
} from '../../components/Charts';
import { getTimeDistance } from '../../utils/utils';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import SwitchRole from '../../components/SwitchRole';
import styles from './Analysis.less';
const { RangePicker } = DatePicker;
const TabPane = Tabs.TabPane;
import Debounce from 'lodash-decorators/debounce';
import request from '../../utils/request';
import Title from '../../components/Statistics/Title';
import {CallMonth,CallWeek,CallDay} from '../../components/Statistics/CallStatistics';
import {listParams,callState} from '../defaultData';
import {findObjByKey,convertLongToString} from '../../utils/index';
@connect(state=>({
  group:state.group,
  userManage:state.usermanagement
}))
export default class extends Component{
  state={
    rangePickerValue: [],
    daySendData:{},
    weekSendData:{},
    monthSendData:{},
    defaultType:'today',  // today week month year
    dayData:[],
    weekData:[],
    monthData:[],
    callData:{},
    callList:[],
    key:Math.random(),
    isvisible:false,
    title:"",
    searchInfo:{
      radio:1,
      selectArr:[]
    },
    countList:[],
    countListVisible:false,
    pagination:{
      ...listParams,
      total:0
    }
  }
  selectDate = (type) => {
    let momentArr=getTimeDistance(type);
    this.setState({
      rangePickerValue:momentArr ,
    },()=>{
      this.getCountData();
    });
  }
  isActive(type) {
    const { rangePickerValue } = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return;
    }
    if (rangePickerValue[0].isSame(value[0], 'day') && rangePickerValue[1].isSame(value[1], 'day')) {
      return styles.currentDate;
    }
  }
  handleRangePickerChange = (rangePickerValue,dateString) => {
    this.setState({
      rangePickerValue,
    },()=>{
      this.getCountData()
    });
  }



  @Debounce(500)
  getDayData=(params)=>{
    if(!params){
      params=this.state.daySendData;
    }
    let {start,end} = params;
    //为空时不做处理
    if(start === end && !end){
      return;
    }
    this.setState({daySendData:params});
    this.getList({
      ...params,
      periodType:'DAY'
    });
  }
  @Debounce(500)
  getWeekData=(params)=>{
    if(!params){
      params=this.state.weekSendData;
    }
    let {start,end} = params;
    //为空时不做处理
    if(start === end && !end){
      return;
    }
    this.setState({weekSendData:params});
    this.getList({
      ...params,
      periodType:'WEEK'
    });

  }
  @Debounce(500)
  getMonthData=(params)=>{
    if(!params){
      params=this.state.monthSendData;
    }
    let {start,end} = params;
    //为空时不做处理
    if(start === end && !end){
      return;
    }
    this.setState({monthSendData:params});
    this.getList({
      ...params,
      periodType:'MONTH'
    });

  }
  getList=(params)=>{
    let {start,end,periodType}=params;
    this.setState({
      searchListParams:params
      }
    )
    if(start){
      params.start=start.format("YYYY-MM-DD")+' 00:00:00';
    }
    if(end){
      params.end=end.format("YYYY-MM-DD")+' 23:59:59';
    }
    let _this=this;
    let {searchInfo} = this.state;
    let stateName=periodType=='DAY'?'dayData':(periodType=='WEEK'?'weekData':'monthData');
    if(searchInfo.selectArr.length==0){
      this.setState({
        [stateName]:[]
      })
    }
    if(searchInfo.radio==1){
      params.groupIds=searchInfo.selectArr;
    }else{
      params.userIds=searchInfo.selectArr;
    }
    request(`/v1/call/statistics/chart`,{
      method:'POST',
      body:{
        ...params
      }
    }).then(jsonData=>{
      console.log('chart',jsonData,params)
      if(jsonData.result){
        let data=jsonData.data || [];
        _this.setState({
          [stateName]:data
        })
        /*if(periodType==='DAY'){
          _this.setState({
            dayData:data
          })
        }
        if(periodType==='WEEK'){
          _this.setState({
            weekData:data
          })
        }
        if(periodType==='MONTH'){
          _this.setState({
            monthData:data
          })
        }*/
      }
    })
  }
  getUserList=()=>{
    let _this=this;
    this.props.dispatch({
      type:'group/fetchList',
      payload:{}
    });
    this.props.dispatch({
      type:'group/fetchSameGroupUserList',
      payload:{}
    })
  }

  getCountData=()=>{
    let {searchInfo,rangePickerValue} = this.state;
    let params={};
    if(searchInfo.radio==1){
      params.groupIds=searchInfo.selectArr;
    }else{
      params.userIds=searchInfo.selectArr;
    }
    if(rangePickerValue.length>0){
      params.start=rangePickerValue[0].format("YYYY-MM-DD")+' 00:00:00';
      params.end=rangePickerValue[1].format("YYYY-MM-DD")+' 23:59:59';
    };
    let _this=this;
    request('/v1/call/statistics/count',{
      method:'POST',
      body:{
        ...params
      }
    }).then(jsonData=>{
      console.log('count',jsonData,params)
      if(jsonData.result){
       _this.setState({
         callData:jsonData.data
       })
      }
    })
  }

  getData=(params)=>{
    let {radio,selectArr} = params;
    let title='';
    if(selectArr.length>0){
      let arr= radio==1? this.props.group.groupList : this.props.group.sameGroupList;
      if(selectArr.length==arr.length){
        title=radio==1?'全部分组':'全部组员';
      }else{
        let nameArr=[];
        selectArr.forEach(one=>{
          let obj=arr.find(item=>item.id==one) || {};
          if(obj){
            nameArr.push(obj.name || obj.userName);
          }
        })
        title=nameArr.join('，');
      }
    }
    this.setState({
      searchInfo:params,
      isvisible:false,
      title
    },()=>{
      this.getCountData();
      this.getWeekData();
      this.getDayData();
      this.getMonthData();
    })
  }

  setCountListType=(type)=>{
    this.callState=type;
    this.getCountList();
  }

  getCountList=(page={current:1})=>{
    let {searchInfo,rangePickerValue} = this.state;
    let pagination={
      ...this.state.pagination,
      ...page
    }
    let params={
      callState:this.callState,
      ...pagination
    };
    if(searchInfo.radio==1){
      params.groupIds=searchInfo.selectArr;
    }else{
      params.userIds=searchInfo.selectArr;
    }
    if(rangePickerValue.length>0){
      params.start=rangePickerValue[0].format("YYYY-MM-DD")+' 00:00:00';
      params.end=rangePickerValue[1].format("YYYY-MM-DD")+' 23:59:59';
    };
    params.page=params.current;
    let _this=this;
    request(`/v1/call/statistics/count/list`,{
      method:"POST",
      body:{
        ...params
      }
    }).then(jsonData=>{
      if(jsonData.result){
        let data=jsonData.data || {};
        let {list,total} = data;
        pagination.total=total || 0;
        _this.setState({
          countList:list || [],
          countListVisible:true,
          pagination
        })
      }else{
        message.error(jsonData.msg || '获取错误');
      }
    })
  }

  columns=[
    {title:'客服名称',dataIndex:'callerName'},
    {title:'客户名称',dataIndex:'customerName'},
    {title:'客户类型',dataIndex:'customerType',render:(type)=>{
      return type=='PUBLIC'?'公共':'私有';
    }},
    {title:'拨打时间',dataIndex:'callTime',render:(time)=>{
      return time? convertLongToString(time) :'';
    }},
    {title:'通话时长',dataIndex:'duration',render:(times)=>{
        if(times==0 || times){
          return this.getTimeStr(times);
        }
        return '';
    }},
    {title:'分机号',dataIndex:'agentNo'},
    {title:'统计类型',dataIndex:'callState',render:(state)=>{
      return state?findObjByKey(callState,state).name :'';
    }},]
  getTimeStr=(times=0)=>{
    let hour=Math.floor(times/(60*60));
    let min=Math.floor((times-hour*60*60)/60);
    let sec=times-hour*60*60 - min*60;
    if(hour>0){
      return `${hour}时${min}分${sec}秒`;
    }
    if(min>0){
      return `${min}分${sec}秒`;
    }
    return `${sec}秒`
  }

  componentDidMount(){
    this.selectDate(this.state.defaultType);
    this.getUserList();
  }
  render(){
    let {rangePickerValue} = this.state;
    let {group} = this.props;
    const topColResponsiveProps = {
      span:4
    };
    const salesExtra = (
      <div className={styles.salesExtraWrap}>
        <div className={styles.salesExtra}>
          <a className={this.isActive('today')} onClick={() => this.selectDate('today')}>
            今日
          </a>
          <a className={this.isActive('week')} onClick={() => this.selectDate('week')}>
            本周
          </a>
          <a className={this.isActive('month')} onClick={() => this.selectDate('month')}>
            本月
          </a>
          <a className={this.isActive('year')} onClick={() => this.selectDate('year')}>
            全年
          </a>
        </div>
        <RangePicker
          value={rangePickerValue}
          onChange={this.handleRangePickerChange}
          style={{ width: 256 }}
        />
      </div>
    );
    let {callData} = this.state;
    return(<div>
      <PageHeaderLayout title="通话统计">
        <Title content={this.state.title} showButton={true} onClick={()=>{
          this.setState({
            isvisible:true,
            key:Math.random()
          })
        }} />
        <Card extra={salesExtra} title="统计" style={{marginTop:20}}>
          <Row gutter={24}>
            <Col {...topColResponsiveProps}>
              <div style={{textAlign:'center'}} className={styles.oneData} onClick={this.setCountListType.bind(this,'START')}>
                <span>拨打数</span>
                <p>{callData.callNum || 0}</p>
              </div>
            </Col>
            <Col {...topColResponsiveProps}>
              <div style={{textAlign:'center'}} className={styles.oneData} onClick={this.setCountListType.bind(this,'ACCESS')}>
                <span >拨通数</span>
                <p>{callData.accessNum || 0}</p>
              </div>
            </Col>
            <Col {...topColResponsiveProps}>
              <div style={{textAlign:'center'}} className={styles.oneData} onClick={this.setCountListType.bind(this,'LOST')}>
                <span>未接通数</span>
                <p>{callData.lostNum || 0}</p>
              </div>
            </Col>
            <Col {...topColResponsiveProps}>
              <div style={{textAlign:'center'}} className={styles.oneData}>
                <span>无效数</span>
                <p>{callData.invalidNum || 0}</p>
              </div>
            </Col>
            <Col {...topColResponsiveProps}>
              <div style={{textAlign:'center'}} className={styles.oneData}>
                <span>通话时长</span>
                <p>{callData.totalDuration || 0}<span style={{fontSize:18}}>min</span></p>
              </div>
            </Col>
            <Col {...topColResponsiveProps}>
              <div style={{textAlign:'center'}} className={styles.oneData}>
                <span>费用</span>
                <p>￥{callData.totalCost==undefined?'':callData.totalCost}</p>
              </div>
            </Col>
          </Row>
        </Card>
        <Row style={{marginTop:20}}>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="接通率"
              total={`${callData.accessRate || 0}%`}
              footer={null}
              contentHeight={46}
            >
              <Progress percent={callData.accessRate || 0} showInfo={false} />
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps} style={{marginLeft:20}}>
            <ChartCard
              bordered={false}
              title="平均接通时长"
              total={`${callData.avgDuration || 0}Min`}
              footer={null}
              contentHeight={46}
            >
              <div style={{height:21,width:10}}></div>
            </ChartCard>
          </Col>
        </Row>
        <div style={{marginTop:40,padding:40,backgroundColor:"#fff"}}>
          <Tabs type="card">
            <TabPane tab="日" key="1"><CallDay getData={this.getDayData} data={this.state.dayData}/></TabPane>
            <TabPane tab="周" key="2"><CallWeek getData={this.getWeekData} data={this.state.weekData}/></TabPane>
            <TabPane tab="月" key="3"><CallMonth getData={this.getMonthData} data={this.state.monthData}/></TabPane>
          </Tabs>
        </div>
        <SwitchRole userList={group.sameGroupList || [] }
                    groupList={group.groupList || [] }
                    isvisible={this.state.isvisible}
                    onSubmit={this.getData}
                    {...this.state.searchInfo}
                    onCancel={()=>{
                      this.setState({
                        isvisible:false
                      })
                    }}
        />
        <Modal title="通话列表"
               visible={this.state.countListVisible}
                width="800"
                onCancel={()=>{
                    this.setState({
                    countListVisible:false
                  })
              }}>
          <Table rowKey="recordId"
                 columns={this.columns}
                 dataSource={this.state.countList}
                 pagination={{...this.state.pagination}}
                 onChange={this.getCountList} />
        </Modal>
      </PageHeaderLayout>

    </div>)
  }
}
